import { loginApi, registerApi } from '@/api';
import { useCookies } from '@vueuse/integrations/useCookies';
import { defineStore } from 'pinia';

const { VITE_TOKEN_KEY } = import.meta.env;

interface StoreUser {
  token: string;
  info: Record<any, any>;
  infoList: Array<any>;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): StoreUser => ({
    token: '',
    info: {},
    infoList: [],
  }),
  getters: {
    getUserInfo(): any {
      return this.info || {};
    },
  },
  actions: {
    setToken(token: any) {
      this.token = token || '';
      sessionStorage.setItem('token', token || '');
    },
    setUserInfo(info: any) {
      this.info = info ? info : {};
    },
    login(data) {
      return new Promise((resolve) => {
        loginApi(data)
          .then((res) => {
            if (res && res.token) {
              ElMessage.success(res.message || res.errmsg);
              this.setToken(res.token);
              resolve(res);
            } else {
              ElMessage.error(res.message || res.errmsg);
              resolve(res);
            }
          })
          .catch((err) => {
            console.log('err', err);
            ElMessage.error(err.message);
            resolve(err);
          });
      });
    },
    register(data) {
      return new Promise((resolve) => {
        registerApi(data)
          .then((res) => {
            if (res && res.token) {
              ElMessage.success(res.message || res.errmsg);
              this.setToken(res.token);
              resolve(res);
            } else {
              ElMessage.error(res.message || res.errmsg);
              resolve(res);
            }
          })
          .catch((err) => {
            console.log('err', err);
            ElMessage.error(err.message);
            resolve(err);
          });
      });
    },
  },
  persist: {
    key: 'token',
    storage: sessionStorage,
    paths: ['token', 'info'],
  },
});
